package com.abxh.media.audio

import android.os.Bundle
import android.util.Log
import android.util.Size
import android.view.SurfaceView
import android.view.View
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.abxh.core.MmkvHelper
import com.abxh.jetpack.base.BaseViewModelActivity
import kotlinx.coroutines.async
import okio.Okio
import java.io.File
import java.util.concurrent.ExecutionException

/**
 * Created by dab on 2021/9/11 10:40
 */
public class MediaRecordActivity : BaseViewModelActivity<MediaViewModel>() {
    var tagSize = Size(480, 680)
    var ultimateSize: Size? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_record)
        initCamera()
        findViewById<View>(R.id.start).setOnClickListener {
//            val file = File(getExternalFilesDir(Environment.DIRECTORY_MOVIES)!!.path, "${System.currentTimeMillis()}.h264")
            val dirPath = (getExternalFilesDir("")!!.absolutePath + File.separator + "TestRecode")
            val currentTimeMillis = System.currentTimeMillis()
            val videoPath =
                "${dirPath}${File.separator}${currentTimeMillis}${File.separator}${currentTimeMillis}.h264"
            val audioPath =
                "${dirPath}${File.separator}${currentTimeMillis}${File.separator}${currentTimeMillis}.aac"
            videoPath.toFile()?.let { videoFile ->
                MmkvHelper.getInstance().putString("videoPath", videoFile.absolutePath)
                audioPath.toFile()?.let { audioFile ->
                    ultimateSize?.let {
                        lifecycleScope.launchWhenResumed {
                            async { viewModel.startVideo(videoFile, it) }
                            async { viewModel.startAudio(audioFile) }
                        }
                    }
                }
            }
//            MmkvHelper.getInstance().putString("videoPath", videoPath?.absolutePath)


        }
        findViewById<View>(R.id.play).setOnClickListener {
            val videoPath = MmkvHelper.getInstance().getString("videoPath", "")
            Log.e("TAG", "onCreate: *****************$videoPath")
            val svContent = findViewById<SurfaceView>(R.id.sv_content)
            val holder = svContent.holder
            val buffer = Okio.buffer(Okio.source(File(videoPath)))
            buffer.use {
                viewModel.playVideo(holder, it)
            }
        }
    }

    private fun initCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            try {
                bindPreview(cameraProviderFuture.get(), findViewById<PreviewView>(R.id.pv_content))
            } catch (e: ExecutionException) {
                e.printStackTrace()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }, ContextCompat.getMainExecutor(this))
    }

    private fun bindPreview(
        processCameraProvider: ProcessCameraProvider,
        previewView: PreviewView
    ) {

        val preview = Preview.Builder().setTargetResolution(tagSize).build()
        val cameraSelector =
            CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()
        processCameraProvider.unbindAll()
        preview.setSurfaceProvider(previewView.surfaceProvider)
        val camera =
            processCameraProvider.bindToLifecycle(this, cameraSelector, preview, getAnalysis())
    }

    //Analysis和Priview中设置的分辨率可以不同，这说明分析图片和预览图片是可以分开应用的。
    private fun getAnalysis(): ImageAnalysis {
        return ImageAnalysis.Builder().build().apply {
            setAnalyzer(ContextCompat.getMainExecutor(this@MediaRecordActivity), {
                if (ultimateSize == null) {
                    ultimateSize = Size(it.width, it.height)
                }
                viewModel.put(it)
                it.close()
            })
        }
    }
}